package com.chenfan.ccp.autoconfigure;

import com.chenfan.ccp.plug.log.config.DynamicDataSourceConfig;
import com.chenfan.ccp.plug.log.config.FeignInterceptorConfig;
import com.chenfan.ccp.plug.log.config.NativeServletFilter;
import com.chenfan.ccp.annotation.NativeServletEnv;
import feign.RequestHeaderForwardFeignInterceptorConfig;
import com.chenfan.ccp.plug.business.parser.DefaultUserIdParser;
import com.chenfan.ccp.plug.business.parser.UserIdParser;
import feign.RequestInterceptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;


@Configuration
@ConditionalOnProperty(
        name = {"spring.application.name"},
        matchIfMissing = true
)
@NativeServletEnv
public class GlobalNativeServletAutoConfigure extends AbstractAutoConfigure {

    private static final String INTERCEPTOR_PATH = "/*";

    @Bean
    @ConditionalOnBean(DataSource.class)
    public DynamicDataSourceConfig dynamicDataSourceConfig() {
        return new DynamicDataSourceConfig();
    }

    /**
     * filter的注入
     *
     * @return
     */
    @Bean
    public NativeServletFilter nativeServlerFilter() {
        return new NativeServletFilter();
    }


    /**
     * 注册自定义过滤器
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean createCustomFilter(NativeServletFilter.CustomFilter customFilter) {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(customFilter);
        filterRegistrationBean.addUrlPatterns(INTERCEPTOR_PATH);
        filterRegistrationBean.setOrder(Integer.MAX_VALUE);
        return filterRegistrationBean;
    }

    /**
     * 注册过滤器
     *
     * @return
     */
    @Bean
    public NativeServletFilter.CustomFilter createCustomFilterBean(UserIdParser userIdParser) {
        return new NativeServletFilter.CustomFilter(userIdParser);
    }

    @Bean
    @ConditionalOnMissingBean
    public UserIdParser userIdParser() {
        return new DefaultUserIdParser();
    }

    /**
     * feign拦截器
     */

    @Bean
    public RequestInterceptor requestInterceptor() {
        return new FeignInterceptorConfig();
    }
    @Bean
    public RequestInterceptor requestHeaderForwardFeignInterceptorConfig(){
     return new RequestHeaderForwardFeignInterceptorConfig();
    }


}
